package br.sales.view.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import br.sales.view.util.ViewUtil;

@FacesValidator(value="emailValidator")
public class EmailValidator implements Validator{

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
	
			String email = (String) value;

	        Pattern pattern = Pattern.compile("^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$");
	        Matcher matcher = pattern.matcher(email);
	        
	        if (!matcher.find()) {
	            FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, ViewUtil.getResourceBundle(FacesContext.getCurrentInstance(),"invalid_email"), null); 
	            throw new ValidatorException(facesMessage);
	        }

	        if (!matcher.matches()) {
	        	FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, ViewUtil.getResourceBundle(FacesContext.getCurrentInstance(),"invalid_email"), null);
	            throw new ValidatorException(facesMessage);
	        }
	}

}
